package com.dmwork.service.oss.controller;

import com.dmwork.common.base.result.ExceptionUtils;
import com.dmwork.common.base.result.R;
import com.dmwork.common.base.result.ResultCodeEnum;
import com.dmwork.service.base.model.FileUrlVo;
import com.dmwork.service.oss.service.FileService;
import com.dmwork.service.base.exception.DmworkException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Api(description = "阿里云文件管理")
@Slf4j
@RestController
@RequestMapping("/dm_work/oss/file")
public class OssController {

    @Autowired
    private FileService fileService;

    @ApiOperation("文件上传")
    @PostMapping("upload")
    public R upload(@ApiParam(value = "模块", required = true) @RequestParam("module") String module,
                    @ApiParam(value = "文件", required = true) @RequestParam("file") MultipartFile file){
        String uploadUrl=null;
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            uploadUrl=fileService.upload(inputStream, module, originalFilename);
        } catch (IOException e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new DmworkException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
        return R.ok().data("url", uploadUrl);
    }

    @ApiOperation("单个文件删除")
    @DeleteMapping("remove")
    public R removeFile(@ApiParam("文件url") @RequestBody FileUrlVo urlVo){
        log.info("urlVo=>>>>>>>>>>"+urlVo.toString());
        fileService.fileRemove(urlVo.getUrl());
        return R.ok().message("删除文件成功");
    }

    @ApiOperation("文件批量删除")
    @DeleteMapping("batch_remove")
    public R removeBatchFile(@ApiParam("文件url列表") @RequestBody FileUrlVo fileUrlVo) {
        fileService.fileBatchRemove(fileUrlVo.getUrlList());
        return R.ok().message("删除成功");
    }

}
